package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/ichub/gofactroy/common/ichubbase"
	"gitee.com/ichub/gofactroy/nats/msg2nets"
	"github.com/nats-io/nats.go"

	"log"
	"time"
)

var Nc *nats.Conn

// 邀请码注册消息主题
const SubjReg = "UserRegMsg2Cms"
const Nats_URL = "nats://192.168.4.111:4222"
const SubjOrder = "OrderFinishMsg2Cms"

// AdCode
type OrderFinishMsg2Cms struct {
	//广告码
	AdCode string
	//用户id
	UserId int64
	//订单标识
	OrderId     string
	OrderLineId []string

	//订单完成时间 s
	FinishedTime int64
}

// 前端链接注册，header增加邀请码 InviteCode
type UserRegMsg2Cms struct {
	//邀请注册
	//邀请码
	InviteCode string
	//ShopID
	//用户id
	UserId int64
	//注册时间 s
	RegTime int64
}

func (entity *UserRegMsg2Cms) String() string {
	s, err := json.Marshal(entity)
	if err != nil {
		fmt.Println(err.Error())
		return "{}"
	}
	return string(s)

}

func (entity *UserRegMsg2Cms) ToString() string {
	s, err := json.MarshalIndent(entity, "", " ")
	if err != nil {
		fmt.Println(err.Error())
		return "{}"
	}
	return string(s)

}
func (entity *UserRegMsg2Cms) Unmarshal(body string) error {
	return json.Unmarshal([]byte(body), entity)

}
func roachDBUrlConnPG() string {
	return "postgresql://root@192.168.4.119:26257/" + ichubbase.MODULE_MAP[ichubbase.APP].DBNAME + "?sslmode=disable"

}

var natsManager msg2nats.NatsManager

func main() {
	//
	//tabletool := &dbtool.TableTool{
	//	Dbtype_mysql: false,
	//	Db:          ichubbase.MODULE_MAP[ichubbase.APP].DBNAME,
	//	Table:        "employee",
	//	Author:       "leijianming",
	//	ModuleName:   ichubbase.MODULE_MAP[ichubbase.APP],
	//}
	//
	//dBUrl := roachDBUrlConnPG()
	//var dbinst *gorm.DB = tabletool.InitDb(dBUrl)
	//defer dbinst.Close()

	nc, err := nats.Connect(Nats_URL)
	Nc = nc

	if err != nil {
		log.Fatal(err)
	}
	defer Nc.Close()

	natsMessage := msg2nats.NatsMessage{}
	natsMessage.Header.Topic = SubjReg
	natsMessage.Header.Version = "V1"

	natsManager = msg2nats.NatsManager{
		Nc: nc,
	}

	natsManager.Ini()
	regMsg := UserRegMsg2Cms{}

	regMsg.InviteCode = "A31234"
	regMsg.RegTime = time.Now().UTC().Unix()
	regMsg.UserId = -1111
	natsMessage.IniData([]byte(regMsg.String()))

	err = natsManager.Publish(natsMessage)
	err = natsManager.Publish(natsMessage)

	err = natsManager.Publish(natsMessage)
	if err != nil {
		fmt.Println(err)
		return
	}
	natsMessage.IniData([]byte(regMsg.String()))

	for true {

		err = natsManager.Publish(natsMessage)
		if err != nil {
			fmt.Println(err)
		}
		time.Sleep(1e7)
		break
	}
	time.Sleep(1e7)

}
